route.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { createParser } from "eventsource-parser";
  2. import { NextRequest, NextResponse } from "next/server";
  3. import { auth } from "../../auth";
  4. import { requestOpenai } from "../../common";
  5. async function createStream(res: Response) {
  6. const encoder = new TextEncoder();
  7. const decoder = new TextDecoder();
  8. const stream = new ReadableStream({
  9. async start(controller) {
  10. function onParse(event: any) {
  11. if (event.type === "event") {
  12. const data = event.data;
  13. // https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream
  14. if (data === "[DONE]") {
  15. controller.close();
  16. return;
  17. }
  18. try {
  19. const json = JSON.parse(data);
  20. const text = json.choices[0].delta.content;
  21. const queue = encoder.encode(text);
  22. controller.enqueue(queue);
  23. } catch (e) {
  24. controller.error(e);
  25. }
  26. }
  27. }
  28. const parser = createParser(onParse);
  29. for await (const chunk of res.body as any) {
  30. parser.feed(decoder.decode(chunk, { stream: true }));
  31. }
  32. },
  33. });
  34. return stream;
  35. }
  36. function formatResponse(msg: any) {
  37. const jsonMsg = ["```json\n", JSON.stringify(msg, null, " "), "\n```"].join(
  38. "",
  39. );
  40. return new Response(jsonMsg);
  41. }
  42. async function handle(
  43. req: NextRequest,
  44. { params }: { params: { path: string[] } },
  45. ) {
  46. console.log("[OpenAI Route] params ", params);
  47. const authResult = auth(req);
  48. if (authResult.error) {
  49. return NextResponse.json(authResult, {
  50. status: 401,
  51. });
  52. }
  53. try {
  54. const api = await requestOpenai(req);
  55. const contentType = api.headers.get("Content-Type") ?? "";
  56. // streaming response
  57. if (contentType.includes("stream")) {
  58. const stream = await createStream(api);
  59. const res = new Response(stream);
  60. res.headers.set("Content-Type", contentType);
  61. return res;
  62. }
  63. // try to parse error msg
  64. try {
  65. const mayBeErrorBody = await api.json();
  66. if (mayBeErrorBody.error) {
  67. console.error("[OpenAI Response] ", mayBeErrorBody);
  68. return formatResponse(mayBeErrorBody);
  69. } else {
  70. const res = new Response(JSON.stringify(mayBeErrorBody));
  71. res.headers.set("Content-Type", "application/json");
  72. res.headers.set("Cache-Control", "no-cache");
  73. return res;
  74. }
  75. } catch (e) {
  76. console.error("[OpenAI Parse] ", e);
  77. return formatResponse({
  78. msg: "invalid response from openai server",
  79. error: e,
  80. });
  81. }
  82. } catch (e) {
  83. console.error("[OpenAI] ", e);
  84. return formatResponse(e);
  85. }
  86. }
  87. export const GET = handle;
  88. export const POST = handle;
  89. export const runtime = "edge";